import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Http, Jsonp,Headers } from "@angular/http";
import { ConfigProvider } from "../../providers/config/config";

/*
  Generated class for the HttpserviesProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
  封装公共请求服务
*/
@Injectable()
export class HttpserviesProvider {

  public allurl = '';

  //设置post格式
  private headers =new Headers({'Content-Type': 'application/json'});

  constructor(public http:Http ,public jsonp:Jsonp, public config:ConfigProvider) {
    console.log('Hello HttpserviesProvider Provider');
  }

  //1.Get请求数据， 获取显示数据
  // apiUrl :   api/focus
  // apiUrl :   api/plist?page=1
  requestData(url,callback){
    //若请求路径中包含”?“，则用”&“拼接后面的callback=JSONP_CALLBACK，反之则用”?“拼接
    if(url.indexOf('?') == -1){
      this.allurl = this.config.apiUrl+url+'?callback=JSONP_CALLBACK'; 
    }else{
      this.allurl = this.config.apiUrl+url+'&callback=JSONP_CALLBACK';
    }

    //(data)=> 相当于function(data) (data)=>中的this指的是当前对象
    this.jsonp.get(this.allurl).subscribe((data)=>{
      //回调函数
      callback(data['_body']);
    },function(err){
      console.log('请求错误');
      console.log(err);
    })
  }

  //2.post请求， 一般情况用来提交数据
  doPostData(url,json,callback){
    var allurl = this.config.apiUrl+url;
    this.http.post(allurl, JSON.stringify(json),{headers:this.headers}).subscribe((data)=>{
      callback(data.json());
    },function(err){
      console.log('请求错误');
      console.log(err);
    })
  }

}
